package com.regedit.aplicacion.activities;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.regedit.aplicacion.R;
import com.regedit.aplicacion.adapters.MiAdapter;
import com.regedit.aplicacion.adapters.MiCursorAdapter;
import com.regedit.aplicacion.controllers.BDController;
import com.regedit.aplicacion.controllers.CarroController;
import com.regedit.aplicacion.dao.DatabaseHelper;
import com.regedit.aplicacion.dao.EntityDao;
import com.regedit.aplicacion.models.Carro;
import com.regedit.aplicacion.utils.MiHilo;

public class BienvenidoActivity extends Activity {

	private Context mContext;
	private ListView lista;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bienvenido);
		mContext = this;
		String nombre = getIntent().getExtras().getString("nombre");
		lista = (ListView) findViewById(R.id.listView1);
		TextView tView = (TextView) findViewById(R.id.miTextView);
		tView.setText(nombre);

		final EditText editText = (EditText) findViewById(R.id.filtroNombre);
		editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				llenarDataUsandoCP(editText.getText().toString());
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub

			}
		});

		Button btnInsertar = (Button) findViewById(R.id.insertarButton);
		btnInsertar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, InsertActivity.class);
				startActivity(intent);
			}
		});

		Button btnInsertarFake = (Button) findViewById(R.id.insertarFale);
		btnInsertarFake.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Carro carro = new Carro();
				carro.setMarca("Carro Fake");
				getContentResolver().insert(EntityDao.CONTENT_URI,
						EntityDao.contentValuesToInsert(carro));
			}
		});

	}

	@Override
	protected void onResume() {
		super.onResume();
		llenarDataUsandoCP("");
		// creaHilo();
		// llenarDataEnLista("");
	}

	public void llenarDataUsandoCP(String nombre) {
		CarroController cController = new CarroController(mContext);
		Cursor cursor = cController.obtenerCarrosConContentProvider(nombre);
		final String[] arrayFrom = new String[] { EntityDao.COL_TITLE };
		final int[] arrayTo = new int[] { R.id.marca };
		MiCursorAdapter adapter = new MiCursorAdapter(mContext,
				R.layout.nuevo_item_layout, cursor, arrayFrom, arrayTo);
		lista.setAdapter(adapter);

	}

	public void llenarDataEnLista(String nombre) {

		BDController bController = new BDController(this);
		Cursor cursor = bController.getDataByName(nombre);
		ArrayList<Carro> miLista = new ArrayList<Carro>();
		while (!cursor.isAfterLast()) {
			String texto = cursor.getString(cursor
					.getColumnIndexOrThrow(EntityDao.COL_TITLE));
			Carro carro1 = new Carro();
			carro1.setMarca(texto);
			miLista.add(carro1);
			cursor.moveToNext();
		}
		MiAdapter adapter = new MiAdapter(mContext, miLista,
				R.layout.nuevo_item_layout);
		lista.setAdapter(adapter);
	}

	public void updateData() {
		// instancio la clase Helper
		DatabaseHelper mDbHelper = new DatabaseHelper(this);
		// obtengo la db en modo lectura
		SQLiteDatabase db = mDbHelper.getReadableDatabase();

		// New value for one column
		ContentValues values = new ContentValues();
		values.put(EntityDao.COL_TITLE, "BMW222");

		// Which row to update, based on the ID
		String selection = EntityDao.COL_ID + " = ?";
		String[] selectionArgs = { String.valueOf(3) };

		int count = db.update(EntityDao.TABLE_NAME, values, selection,
				selectionArgs);
	}

	public void creaHilo() {
		final ProgressDialog progressDialog = ProgressDialog.show(mContext, "",
				"Cargando...");
		new Thread(new Runnable() {

			@Override
			public void run() {
				CarroController cController = new CarroController(mContext);
				JSONObject json = cController.getCarros();
				final ArrayList<Carro> miLista = new ArrayList<Carro>();
				try {
					JSONArray jArray = json.getJSONArray("list");
					for (int i = 0; i < jArray.length(); i++) {
						JSONObject jsonCarro = jArray.getJSONObject(i);
						Carro carro1 = new Carro();
						carro1.setMarca(jsonCarro.getString("marca"));
						miLista.add(carro1);
					}

				} catch (JSONException e) {
					Log.e("Json", e.getMessage());
				}

				runOnUiThread(new Runnable() {
					public void run() {
						MiAdapter adapter = new MiAdapter(mContext, miLista,
								R.layout.nuevo_item_layout);
						lista.setAdapter(adapter);
						progressDialog.dismiss();
					}
				});

			}
		}).start();

	}

	public void llamarTask() {
		MiHilo task = new MiHilo(mContext);
		task.execute();
	}
}
